#include "constants.h";
#include "done_buildings.sqf";

if (D_CYCLING_BUSY) exitWith {};
D_CYCLING_BUSY = true;

if (isnil "D_HOUSES") then { D_HOUSES = []; };
if (isnil "D_DONE_HOUSES") then { D_DONE_HOUSES = []; };

if (isnil "D_LOCATIONS") exitWith { hint "No locations!" };
if (count D_LOCATIONS <= 0) exitWith { hint "No locations!" };

if (count D_HOUSES <= 0) then {
	_found_buildings =[];
	if (! isnil "D_DONE_HOUSES") then {
		_found_buildings = [_found_buildings, D_DONE_HOUSES] call XfArrayPushStack;
	};
	if (! isnil "D_BUILDING_INDEXER") then {
		_found_buildings = [_found_buildings, D_BUILDING_INDEXER] call XfArrayPushStack;
	};
	diag_log "NEW DONE HOUSES";
	_counter = 0;
	{
		_counter = _counter + 1;
		_center = _x select XF_MAP_LOCATION_CENTER;
		hintsilent Format ["Checking Zone %1",_counter];
		if (count _center > 0) then {
			_radius = 800;
			_bldgs = nearestobjects [_center, ["building"], _radius];
			{
				_type = typeof _x;
				if (!(_type in _found_buildings)) then {
					_found_buildings set [count _found_buildings, _type];
					D_HOUSES set [ count D_HOUSES, _type ];
					diag_log format["%1",_type];
				};
			} foreach _bldgs;
		};
	} foreach D_LOCATIONS;
	hint Format ["Found %1 new buildings!",count D_HOUSES];
};

if (count D_HOUSES > 0) then { 
	_current_house = D_HOUSES select 0;
	hint Format ["%1 Houses left! Now: %2",count D_HOUSES, _current_house];
	D_HOUSES = D_HOUSES - [_current_house];

	player setPos D_PLAYER_START_POS;
	player setDir D_PLAYER_START_DIR;

	If (isnil "D_CURRENT_BUILDING") then { D_CURRENT_BUILDING = objNull; };
	if (!isnull D_CURRENT_BUILDING) then {
		deleteVehicle D_CURRENT_BUILDING;
	};
	sleep 1;
	D_CURRENT_BUILDING = createvehicle [_current_house,D_BUILDING_POS, [], 0, "none"] ;
	D_CURRENT_BUILDING setDir 0;
	sleep 1;
} else {
	hint "No new houses!";
};
D_CYCLING_BUSY = false;